/**
 * @开发版权 云南赢中吉洋智能技术有限公司（YNYZGY）
 * @项目名称 昆明长水机场三维视频融合系统(AVF3D)
 * @版本信息 v1.0
 * @开发人员 zhous
 * @开发日期 2021-03-22
 * @修订日期
 * @描述  ShiroSessionManager 
 */
package com.vf.editor.common.plugins.shiro;

import java.io.Serializable;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.session.Session;
import org.apache.shiro.session.UnknownSessionException;
import org.apache.shiro.session.mgt.SessionKey;
import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.apache.shiro.web.session.mgt.WebSessionKey;

import com.jfinal.log.Log;

public class ShiroSessionManager extends DefaultWebSessionManager {
	protected final Log log = Log.getLog(getClass());
	private static final String TOKEN = "token";

	private static final String REFERENCED_SESSION_ID_SOURCE = "Stateless request";

	@Override
	protected Serializable getSessionId(ServletRequest servletRequest, ServletResponse response) {
		HttpServletRequest request = (HttpServletRequest) servletRequest;
		String sessionId = request.getHeader(TOKEN);// 请求头中有 token 则其值为sessionId
		if (null != sessionId && !"".equals(sessionId) && !"null".contentEquals(sessionId)) {
			log.debug("token=" + sessionId);
			request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_SOURCE, REFERENCED_SESSION_ID_SOURCE);
			request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID, sessionId);
			request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_IS_VALID, Boolean.TRUE);
			return sessionId;
		} else {
			// 否则按默认规则从cookie取sessionId
			return super.getSessionId(request, response);
		}
	}

	@Override
	protected Session retrieveSession(SessionKey sessionKey) throws UnknownSessionException {
		Serializable sessionId = getSessionId(sessionKey);
		ServletRequest request = null;
		if (sessionId instanceof WebSessionKey) {
			request = ((WebSessionKey) sessionKey).getServletRequest();
		}
		if (request != null && sessionId != null) {
			return (Session) request.getAttribute(sessionId.toString());
		}
		Session session = super.retrieveSession(sessionKey);
		if (request != null && sessionId != null) {
			request.setAttribute(sessionId.toString(), session);
		}
		return session;
	}
}
